package com.ce.pms.customer.web;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.ce.pms.common.web.ICacheManage;
import com.ce.pms.customer.service.ILesseeService;
import com.ce.pms.customer.vo.CustomerHouseVO;
import com.ce.pms.customer.vo.CustomerVO;
import com.ce.pms.customer.vo.IndividualVO;
import com.ce.pms.customer.vo.InterestVO;
import com.ce.pms.customer.vo.OrganizationVO;
import com.ce.pms.exception.BusinessException;
import com.ce.util.BlankUtil;
import com.ce.util.DateUtil;
import com.sitechasia.webx.core.annotation.Read;

/**
 * 功能描述:
 * <p>版权所有：中企动力
 * <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
 *
 * @author  燕大为
 * Created on  2008-5-28
 * @author
 * update on
 */
public class LesseeAction extends CustomerAction {

	/**
	 * 房屋信息集合key
	 */
	public static final String WEBCACHE_KEY_LESSEE_HOUSE = "lesseeHouseColletion";

	/**
	 * Function:
	 * @param currentPage
	 * @param pageSize
	 * @return
	 * Create author:许海堆
	 * Create on:2008-6-3
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	@SuppressWarnings("unchecked")
	public String findLesseeHouseCachePage(@Read(key = "ec_p", defaultValue = "1") Integer currentPage,
											@Read(key = "ec_crd",defaultValue = "5")Integer pageSize){

		List<CustomerHouseVO> resultList = findLesseeHouseListCacheInner(currentPage,pageSize);

		setAttribute("lesseeHouseList", resultList);
		setAttribute("totalRows",getTotalRowsFromCache(WEBCACHE_KEY_LESSEE_HOUSE));
		return "initLesseeHouseList";
	}

	/**
	 * Function:租户的增加，修改，和详细的房间列表
	 * @param currentPage
	 * @param pageSize
	 * @return
	 * Create author:许海堆
	 * Create on:2008-6-3
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	@SuppressWarnings("unchecked")
	private List findLesseeHouseListCacheInner(Integer currentPage,Integer pageSize){

		//从cache中取得数据
		LinkedList<CustomerHouseVO> list = getLesseeHouseListCacheHerebyFlag(true);
		if (list==null) {
			list = new LinkedList<CustomerHouseVO>();
		}

		List<CustomerHouseVO> resultList = paginationList(currentPage,pageSize,list);

		return resultList;
	}

	/**
	 * Function: 初始化新增租户信息（增加租户页面最外层的页面）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-28
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeAddMain()
	{
		clearCache();
		return "initLessAddMain";
	}

	/**
	 * Function: 初始化新增租户信息（租户资料tab）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-28
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeBaseAddMain() {
		return "initLesseeBaseAddMain";
	}


	/**
	 * Function: 新增租户（初始化增加房间的页面）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-28
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeHouseAdd()
	{
		return "initLesseeHouseAdd";
	}


	/**
	 * Function: 删除一个已存到缓存中的住房信息
	 * @param houseID
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void deleteCustomerHouseCache(@Read CustomerHouseVO customerHouseVO)
	{
		if (this.deleteOneCustomerHouseFromCache(WEBCACHE_KEY_LESSEE_HOUSE, customerHouseVO)) {
			renderText("true");
		}else{
			renderText("false");
		}
	}

	/**
	 * Function:在缓冲中删除住户资料（包括个人和企业）
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void deleteLesseeBaseCache(@Read CustomerVO customerVO) {
		if (this.deleteOneCustomerBaseFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, customerVO)) {
			this.renderText("true");
		} else{
			this.renderText("false");
		}

	}


	/**
	 * Function: 初始化租户资料列表信息（增加租户时的界面）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-28
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeBaseList(@Read(key = "ec_crd", defaultValue = "5") int pageSize,
			@Read(key = "ec_p", defaultValue = "1")	int pageNo){

		List<CustomerVO> customerList=findCustomerBaseListCachePage(pageNo,pageSize);
		setAttribute("lesseeBaseList", customerList);
		setAttribute("totalRows",getTotalRowsFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL));
		return "initLesseeBaseList";
	}

	/**
	 * Function: 初始化新增租户信息（个人或者企业）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-29
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLessBaseAdd()
	{
//		初始化下拉列表
		getRequest().setAttribute("certificateTypes", getCertificateType());
		getRequest().setAttribute("consignerCertificateTypes", getCertificateType());
		List<InterestVO> listAll = getAllInterestList();

		getRequest().setAttribute("interestes", listAll);

		return "initLesseeAdd";
	}


	/**
	 * Function:初始化个人或者企业的信息（新增租户信息-->租户列表->修改操作初始化）
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeBaseEdit(@Read(key = "lesseeBaseIndex")Integer index,
			@Read(key="participantTypeCode") String participantTypeCode) {
		List certificateTypeList = getCertificateType();
		List<InterestVO> notSelectList = getAllInterestList();
		List<InterestVO> selectedInterestList = new ArrayList<InterestVO>();
		setAttribute("certificateTypeList", certificateTypeList);

		//这里故意让存在有NullException的可能
		if (participantTypeCode.equals(CustomerVO.INDIVIDUAL_CODE)) {
			IndividualVO individualVO
	        = (IndividualVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        		index);
			String interest = individualVO.getInterest();

			if(!BlankUtil.isBlank(interest))
			{
				if(interest.endsWith(","))
					interest = interest.substring(0, interest.length()-1);
				filtrateExistentInterest(interest, notSelectList, selectedInterestList);
			}

			setAttribute("individualLesseeBase", individualVO);
			setAttribute("IndividualInterestes",selectedInterestList);
			setAttribute("interestes", notSelectList);

			return "lesseeIndividualEdit";
		}else{
			OrganizationVO organizationVO
	        = (OrganizationVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        														  index);
			setAttribute("organization", organizationVO);
			return "lesseeEnterpriseEdit";
		}

	}


	/***
	 * Function: 初始化修改租户内部界面（修改租户时）即租户资料tab
	 * @param participantId
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeBaseEditMain(@Read(key="participantId") Long participantId,
			                             @Read(key="participantTypeCode") String participantTypeCode){

		if(CustomerVO.INDIVIDUAL_CODE.equals(participantTypeCode)) {
			IndividualVO individualVO
	        = (IndividualVO)this.getOneCustomerBaseByIdFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        		participantId);
			getRequest().setAttribute("individual", individualVO);
			String interest = individualVO.getInterest();
			List<InterestVO> notSelectList = getAllInterestList();
			List<InterestVO> selectedInterestList = new ArrayList<InterestVO>();
			if(!BlankUtil.isBlank(interest))
			{
				String interestString = interest.substring(0, interest.length()-1);
				filtrateExistentInterest(interestString, notSelectList, selectedInterestList);
			}
			setAttribute("IndividualInterestes",selectedInterestList);
			setAttribute("interestes", notSelectList);
			getRequest().setAttribute("type", "001");

		}
		if(CustomerVO.ORGNIZATION_CODE.equals(participantTypeCode)) {
			OrganizationVO organizationVO
	        = (OrganizationVO)this.getOneCustomerBaseByIdFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        		participantId);
			getRequest().setAttribute("organization", organizationVO);
			getRequest().setAttribute("type", "002");
		}


		//初始化下拉列表
		getRequest().setAttribute("certificateTypes", getCertificateType());
		getRequest().setAttribute("consignerCertificateTypes", getCertificateType());
		return "initLesseeBaseEditMain";
	}

	/***
	 * Function: 住房详细信息
	 * @return
	 * Create author:燕大为
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeHouseDetail(@Read(key = "ec_p", defaultValue = "1") Integer currentPage,
										@Read(key = "ec_crd",defaultValue = "5")Integer pageSize)
	{
		List<CustomerHouseVO> resultList = findLesseeHouseListCacheInner(currentPage,pageSize);
		setAttribute("lesseeHouseList", resultList);
		setAttribute("totalRows",getTotalRowsFromCache(WEBCACHE_KEY_LESSEE_HOUSE));
		return "initLesseeHouseDetail";
	}

	/**
	 * Function: 初始化租户详细资料主界面（查看租户详细时）
	 * @param participantId
	 * @param customerTypeCode
	 * @return
	 * Create author:燕大为
	 * Create on:2008-6-11
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeDetailMain(@Read(key="participantId") Long participantId, @Read(key = "participantTypeCode") String participantTypeCode )
	{
		clearCache();
		List<CustomerHouseVO> listHouse = customerService.getClientRHouseBy(participantId,CustomerVO.LESSEE_CODE);
		if(!BlankUtil.isBlank(listHouse))
		{
			for(CustomerHouseVO house : listHouse){
		    	addOneCustomerHouseToCache(WEBCACHE_KEY_LESSEE_HOUSE, house, false);
			}
			setAllStatusToDone(LesseeAction.WEBCACHE_KEY_LESSEE_HOUSE);
		}

	    if(CustomerVO.INDIVIDUAL_CODE.equals(participantTypeCode))
		{
	    	IndividualVO individual = customerService.findIndividualById(participantId);
	    	individual.setHasSave(ICacheManage.SAVED);
			individual.setOpratorStatus(ICacheManage.DONE);
	    	wrapIndividualDetail(individual);
	    	getRequest().getSession().setAttribute("lessee_individual", individual);
	    	 this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individual, false);
		}
	    else if(CustomerVO.ORGNIZATION_CODE.equals(participantTypeCode))
	    {
	    	OrganizationVO organization = customerService.findOrganizationById(participantId);
	    	organization.setHasSave(ICacheManage.SAVED);
			organization.setOpratorStatus(ICacheManage.DONE);
			wrapOrganizationDetail(organization);
			getRequest().getSession().setAttribute("lessee_organization", organization);
			this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organization, false);
	    }
	    setAllStatusToDone(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL);

		setAttribute("participantId", participantId.toString());
		setAttribute("participantTypeCode", participantTypeCode);
		return "initLesseeDetailMain";
	}

	/***
	 * Function: 租户详细资料（租户资料tab）
	 * @return
	 * Create author:燕大为
	 * Create on:2008-6-11
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initLesseeBaseDetailMain(@Read(key="participantId") Long participantId, @Read(key = "participantTypeCode") String participantTypeCode )
	{

		if(CustomerVO.INDIVIDUAL_CODE.equals(participantTypeCode))
		{
	    	IndividualVO individual = (IndividualVO) getRequest().getSession().getAttribute("lessee_individual");
	    	setAttribute("individual", individual);
	    	setAttribute("type", CustomerVO.INDIVIDUAL_CODE);
		}
	    else if(CustomerVO.ORGNIZATION_CODE.equals(participantTypeCode))
	    {
	    	OrganizationVO organization = (OrganizationVO) getRequest().getSession().getAttribute("lessee_organization");
	    	setAttribute("organization", organization);
	    	setAttribute("type", CustomerVO.ORGNIZATION_CODE);

	    }

		return "initLesseeBaseDetailMain";
	}

	/**
	 * Function:添加住房信息到缓存
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void addLesseeHouseCache(@Read(key = "ec_p")
	Integer currentPage, @Read(key = "ec_crd")
	Integer pageSize, @Read CustomerHouseVO customerHouseVO) {
		validationHouseOnSave(customerHouseVO.getHouseNumber(),WEBCACHE_KEY_LESSEE_HOUSE);
		//String resStr = this.validationHouseNoRenderText(customerHouseVO.getHouseNumber(),WEBCACHE_KEY_LESSEE_HOUSE);
		//if ("existInList".equalsIgnoreCase(resStr)) {
		//	throw new BusinessException("customer:customer_house_add_fail_exception",BusinessException.WARNING);
		//}
		if(BlankUtil.isBlank(customerHouseVO.getOwnerName())){
			List<CustomerHouseVO> houseList = this.customerService.getHouseAndCustomerBy(customerHouseVO.getHouseNumber());
			if(!BlankUtil.isBlank(houseList)){//有业主
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < houseList.size(); i++) {
					sb.append(houseList.get(i).getOwnerName());
					if(i<houseList.size()-1){
						sb.append(",");
					}
				}
				customerHouseVO.setHouseId(houseList.get(0).getHouseId());
				customerHouseVO.setOwnerName(sb.toString());
			}
			else{
				throw new BusinessException("customer:owner_not_exists",BusinessException.WARNING);
			}
		}
		if(addOneCustomerHouseToCache(WEBCACHE_KEY_LESSEE_HOUSE, customerHouseVO, false)) {
			this.renderText("true");
		} else{
			this.renderText("false");
		}


	}

	/**
	 * Function: 添加一个个人租户到缓存中
	 * @param individualVO
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void addIndividualLesseeToCache(@Read IndividualVO individualVO) {
		individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
		Boolean res = validateCustomerOnSave(individualVO, WEBCACHE_KEY_LESSEE_HOUSE);
//		if (!res) {
//			throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);
//		}
//		super.validateIndividualLoadOnSave(individualVO.getCertificateNo(), individualVO.getCertificateType(), WEBCACHE_KEY_LESSEE_HOUSE);
//		if ("existCache".equalsIgnoreCase(result)) {
//			throw new BusinessException("该住户已经存在列表中了,请重新输入",BusinessException.WARNING);
//		}
		individualVO.setCertificateTypeName(super.getCertifiCateTypeName(individualVO.getCertificateType()));
		individualVO.setCustomerType(CustomerVO.LESSEE_INDIVIDUAL);
		individualVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
		individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
		individualVO.setCreator(getUserId());
		if(this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO, true)) {
		    this.renderText("true");
		} else{
			this.renderText("false");
		}

	}

	/**
	 * Function:添加一个企业租户到缓存中
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void addOrganizationLesseeToCache(@Read OrganizationVO organizationVO) {
		organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
		Boolean res = validateCustomerOnSave(organizationVO, WEBCACHE_KEY_LESSEE_HOUSE);
//		if (!res) {
//			throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);
//		}
//		super.validateOrganizationOnSave(organizationVO.getParticipantName(), WEBCACHE_KEY_LESSEE_HOUSE);
//		if ("existCache".equalsIgnoreCase(result)) {
//			throw new BusinessException("该企业已经存在列表中了,请重新输入",BusinessException.WARNING);
//		}
		organizationVO.setCertificateTypeName(super.getCertifiCateTypeName(organizationVO.getCertificateType()));
		organizationVO.setCustomerType(CustomerVO.LESSEE_ORGNIZATION);
		organizationVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
		organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
		organizationVO.setCreator(getUserId());
		if(this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO, true)) {
			 this.renderText("true");
		} else{
			this.renderText("false");
		}

	}

   /**
	 * Function:增加租户（建立房子和租户的关系）
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-4
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
   @Override
	public String addCustomer() {
	   String Msg="";
	   List<CustomerHouseVO> houseList= this.getLesseeHouseListCacheHerebyFlag(true);//得到住房信息列表
		if (houseList.size()<1) {

			Msg="住房信息不能为空  ";
		}
		houseList= this.getLesseeHouseListCacheHerebyFlag(false);
	   List<CustomerVO> customerList = super.getCustomerBaseListCacheHerebyFlag(true);//得到住户信息列表
		if (customerList.size()<1) {

			Msg=Msg+"租户资料不能为空";
		}
		customerList = super.getCustomerBaseListCacheHerebyFlag(false);
		if(BlankUtil.isBlank(Msg)){
		   Msg=lesseeService.addCustomer(houseList, customerList);
		   if(Msg.equalsIgnoreCase("true")){
			   setAllStatusToDone(WEBCACHE_KEY_LESSEE_HOUSE);
			   setAllStatusToDone(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL);
		   }
		}
		this.renderText(Msg);


	   return null;

   }
   /**
	 * Function: 修改租户企业信息,并保存到缓存
	 * @param organizationVO
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void editOrganizationBaseCache(@Read OrganizationVO organizationVO)
	{
		organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
		Boolean res = validateCustomerOnEditSave(organizationVO, WEBCACHE_KEY_LESSEE_HOUSE,CustomerAction.AT_ADD_EDIT);
//		if (!res) {
//			throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);
//		}
//		super.validateOrganizationOnSave(organizationVO.getParticipantName(), WEBCACHE_KEY_LESSEE_HOUSE);
//		if ("existCache".equalsIgnoreCase(result)) {
//			throw new BusinessException("该企业已经存在列表中了,请重新输入",BusinessException.WARNING);
//		}
		organizationVO.setCreator(getUserId());
		organizationVO.setCertificateTypeName(super.getCertifiCateTypeName(organizationVO.getCertificateType()));

		//如果修改的是同一企业
		if(BlankUtil.isBlank(organizationVO.getParticipantId()) || organizationVO.getParticipantId().equals(organizationVO.getOldParticipantId())){

			if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO)) {
				this.renderText("true");
			} else{
				this.renderText("false");
			}

		} else {  //如果修改了成另一个企业

			OrganizationVO organizationVOTemp
	        = (OrganizationVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        		organizationVO.getIndex());

			boolean successFlat=false;

			//如果还没有保存过的，直接修改就行
			if(ICacheManage.UNSAVE.equals(organizationVOTemp.getHasSave())) {

				organizationVO.setOldConsignerId(null);
				organizationVO.setOldCorporationId(null);
				organizationVO.setOldParticipantId(null);
				if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO)) {
					successFlat = true;
				} else{
					successFlat = false;
				}

			} else {//如果是保存过的，要解除原来的关系，建立新的关系

	            //删除原来的
				CustomerVO customerVO = new CustomerVO();
				customerVO.setIndex(organizationVO.getIndex());
				boolean deleteFlat=this.deleteOneCustomerBaseFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, customerVO);

				if(deleteFlat){
					//建立新的关系
					organizationVO.setCustomerType(CustomerVO.LESSEE_ORGNIZATION);
					organizationVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
					organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
					organizationVO.setOldParticipantId(null);
					organizationVO.setIndex(null);
					successFlat=this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO, true);
				}
			}
			if("true".equals(""+successFlat)){
				this.renderText("true");
			} else {
				this.renderText("false");
			}

		}

	}

	/**
	 * Function:在缓冲中修改个人资料
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void editIndividualBaseCache(@Read IndividualVO individualVO)
	{
		individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
		Boolean res = validateCustomerOnEditSave(individualVO, WEBCACHE_KEY_LESSEE_HOUSE,CustomerAction.AT_ADD_EDIT);
//		if (!res) {
//			throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);
//		}
//		super.validateIndividualLoadOnSave(individualVO.getCertificateNo(), individualVO.getCertificateType(), WEBCACHE_KEY_LESSEE_HOUSE);
//		if ("existCache".equalsIgnoreCase(result)) {
//			throw new BusinessException("该住户已经存在列表中了,请重新输入",BusinessException.WARNING);
//		}
		individualVO.setCreator(getUserId());
		individualVO.setCertificateTypeName(super.getCertifiCateTypeName(individualVO.getCertificateType()));

		//如果修改的是同一个人
		if(BlankUtil.isBlank(individualVO.getParticipantId()) || individualVO.getParticipantId().equals(individualVO.getOldParticipantId())) {

			if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO)) {
				this.renderText("true");
			} else{
				this.renderText("false");
			}

		} else {  //如果修改了成另一个人

			IndividualVO individualVOTemp
	        = (IndividualVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
	        		individualVO.getIndex());

			boolean successFlat=false;

			//如果还没有保存过的，直接修改就行
			if(ICacheManage.UNSAVE.equals(individualVOTemp.getHasSave())) {
				individualVO.setOldParticipantId(null);
				if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO)) {
					successFlat = true;
				} else{
					successFlat = false;
				}

			} else {//如果是保存过的，要解除原来的关系，建立新的关系

				//删除原来的
				CustomerVO customerVO = new CustomerVO();
				customerVO.setIndex(individualVO.getIndex());
				boolean deleteFlat=this.deleteOneCustomerBaseFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, customerVO);


				//增加新的一个个人资料
	            if(deleteFlat){
					individualVO.setCustomerType(CustomerVO.LESSEE_INDIVIDUAL);
					individualVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
					individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
					individualVO.setOldParticipantId(null);
					individualVO.setIndex(null);
					successFlat=this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO, true);
	            }

			}

			if("true".equals(""+successFlat)){
				this.renderText("true");
			} else {
				this.renderText("false");
			}


		}

	}


   /**
	 * Function: 修改租户个人信息
	 * @param individualVO
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:许海堆
	 * Edit on:
	 * Why:
	 */
	public String editLesseeIndividual(@Read IndividualVO individualVO)
	{
		   String Msg="";
		   individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
		   Boolean res = validateCustomerOnEditSave(individualVO, WEBCACHE_KEY_LESSEE_HOUSE,CustomerAction.AT_EDIT);
			if (!res) {
				this.renderText("false");
				throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);

			}
//			String result = super.validateCustomerAllowLoadOnSave(individualVO.getCertificateNo(), individualVO.getCertificateType(), WEBCACHE_KEY_LESSEE_HOUSE);
//			if ("existCache".equalsIgnoreCase(result)) {
//				throw new BusinessException("该住户已经存在列表中了,请重新输入",BusinessException.WARNING);
//			}
		   boolean successFlat=false;
		   individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
		   String certificateTypeName = super.getCertifiCateTypeName(individualVO.getCertificateType());
		   individualVO.setCertificateTypeName(certificateTypeName);
		   List<CustomerHouseVO> houseList= this.getLesseeHouseListCacheHerebyFlag(true);//得到住房信息列表
			if (houseList.size()<1) {

				Msg="houseIsNull";
			}
			houseList= this.getLesseeHouseListCacheHerebyFlag(false);//得到住房信息列表
			if(BlankUtil.isBlank(Msg)){

				individualVO.setCreator(getUserId());

				//如果修改的是同一个人
				if(BlankUtil.isBlank(individualVO.getParticipantId()) || individualVO.getParticipantId().equals(individualVO.getOldParticipantId())) {

					if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO)) {
						successFlat=true;
					} else {
						successFlat=false;
					}


				} else {  //如果修改了另一个人

					IndividualVO individualVOTemp
			        = (IndividualVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
			        		individualVO.getIndex());



					//如果还没有保存过的，直接修改就行
					if(ICacheManage.UNSAVE.equals(individualVOTemp.getHasSave())) {
						individualVO.setOldParticipantId(null);
						if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO)) {
							successFlat = true;
						} else{
							successFlat = false;
						}

					} else {//如果是保存过的，要解除原来的关系，建立新的关系

						//删除原来的
						CustomerVO customerVO = new CustomerVO();
						customerVO.setIndex(individualVO.getIndex());
						boolean deleteFlat=this.deleteOneCustomerBaseFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, customerVO);


						//增加新的一个个人资料
			            if(deleteFlat){
							individualVO.setCustomerType(CustomerVO.LESSEE_INDIVIDUAL);
							individualVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
							individualVO.setParticipantTypeCode(CustomerVO.INDIVIDUAL_CODE);
							individualVO.setOldParticipantId(null);
							individualVO.setIndex(null);
							successFlat=this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, individualVO, true);
			            }

					}



				}

				List<CustomerVO> customerList = super.getCustomerBaseListCacheHerebyFlag(false);//得到住户信息列表

				 if(BlankUtil.isBlank(Msg) && successFlat){
					   Msg=lesseeService.editCustomer(houseList, customerList);
					   if(Msg.equalsIgnoreCase("true")){
						   setAllStatusToDone(WEBCACHE_KEY_LESSEE_HOUSE);
						   setAllStatusToDone(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL);
					   }
					   Msg="true";
				}else {
					Msg="false";
				}


			}
			this.renderText(Msg);


		return null;

	}

	/***
	 * Function: 修改租户企业信息
	 * @param organizationVO
	 * @return
	 * Create author:燕大为
	 * Create on:2008-5-30
	 * Edit author:许海堆
	 * Edit on:
	 * Why:
	 */
	public String editLesseeOrganization(@Read OrganizationVO organizationVO)
	{
		String Msg="";
		boolean successFlat=false;
		organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
		Boolean res = validateCustomerOnEditSave(organizationVO, WEBCACHE_KEY_LESSEE_HOUSE,CustomerAction.AT_EDIT);
		if (!res) {
			throw new BusinessException("customer:customer_add_eidt_save_fail_exception",BusinessException.WARNING);
		}
		   List<CustomerHouseVO> houseList= this.getLesseeHouseListCacheHerebyFlag(false);//得到住房信息列表
			if (houseList.size()<1) {

				Msg="住房信息不能为空  ";
			}


			if(BlankUtil.isBlank(Msg)) {
					organizationVO.setCreator(getUserId());

					//如果修改的是同一企业

					if(BlankUtil.isBlank(organizationVO.getParticipantId()) || organizationVO.getParticipantId().equals(organizationVO.getOldParticipantId())){

						if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO)) {
							successFlat=true;
						} else{
							successFlat=false;
						}

					} else {  //如果修改了另一个企业

						OrganizationVO organizationVOTemp
				        = (OrganizationVO)this.getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL,
				        		organizationVO.getIndex());



						//如果还没有保存过的，直接修改就行
						if(ICacheManage.UNSAVE.equals(organizationVOTemp.getHasSave())) {

							organizationVO.setOldConsignerId(null);
							organizationVO.setOldCorporationId(null);
							organizationVO.setOldParticipantId(null);
							if (this.editOneCustomerBaseAsCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO)) {
								successFlat = true;
							} else{
								successFlat = false;
							}

						} else {//如果是保存过的，要解除原来的关系，建立新的关系

				            //删除原来的
							CustomerVO customerVO = new CustomerVO();
							customerVO.setIndex(organizationVO.getIndex());
							boolean deleteFlat=this.deleteOneCustomerBaseFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, customerVO);

							if(deleteFlat){
								organizationVO.setCustomerType(CustomerVO.LESSEE_ORGNIZATION);
								organizationVO.setCustomerTypeCode(CustomerVO.LESSEE_CODE);
								organizationVO.setParticipantTypeCode(CustomerVO.ORGNIZATION_CODE);
								organizationVO.setOldParticipantId(null);
								organizationVO.setIndex(null);
								successFlat=this.addOneCustomerBaseToCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, organizationVO, true);
							}
						}

					}

					 List<CustomerVO> customerList = super.getCustomerBaseListCacheHerebyFlag(false);//得到住户信息列表

					 if(BlankUtil.isBlank(Msg) && successFlat){
						   Msg=lesseeService.editCustomer(houseList, customerList);
						   if(Msg.equalsIgnoreCase("true")){
							   setAllStatusToDone(WEBCACHE_KEY_LESSEE_HOUSE);
							   setAllStatusToDone(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL);
						   }
						   Msg="true";
					} else {
						Msg="false";
					}

			}

			 this.renderText(Msg);

		return null;
	}

	/**
	 * Function:删除房间列表缓存和租户信息列表缓存
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	protected String clearCache() {
		super.clearCache();
		getRequest().getSession().removeAttribute(WEBCACHE_KEY_LESSEE_HOUSE);
		return null;
	}

	/**
	 * Function:获得在缓存中的房间列表
	 * @param true or false，如果是true，则过滤掉删除状态的，如果还是false，则返回全部的房间列表
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
   @SuppressWarnings("unchecked")
	protected LinkedList<CustomerHouseVO> getLesseeHouseListCacheHerebyFlag(boolean opratorFlag) {
		return super.getCustomerHouseListCacheHerebyFlag(WEBCACHE_KEY_LESSEE_HOUSE, opratorFlag);
	}


   /**
    * Function: 新增租户界面的个人详细信息
    * @param index
    * @return
    * Create author:燕大为
    * Create on:2008-6-11
    * Edit author:
    * Edit on:
    * Why:
    */
	public String getIndividualDetailByIndexFromCache(@Read(key="index") int index) {
		IndividualVO individual =  (IndividualVO) getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, index);
		wrapIndividualDetail(individual);
		setAttribute("individual", individual);
		return "initIndividual";
	}


	/**
	 * Function: 新增租户界面的企业详细信息
	 * @param index
	 * @return
	 * Create author:燕大为
	 * Create on:2008-6-11
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String getOrganizationDetailByIndexFromCache(@Read(key="index") int index) {
		OrganizationVO organization = (OrganizationVO) getOneCustomerBaseByIndexFromCache(CustomerAction.WEBCACHE_KEY_CUSTOMER_ALL, index);
		wrapOrganizationDetail(organization);
		setAttribute("organization", organization);
		return "initOrganization";
	}

	/**
	 * 功能描述:  验证指定房号是否已存在<br>
	 * @param houseNumber
	 * @return
	 * Create author:yandawei <br>
	 * Create on:2008-8-4  <br>
	 * Edit author:  <br>
	 * Edit on:    <br>
	 * Why:     <br>
	 */
	public String validationHouse(@Read(key="houseNumber") String houseNumber) {
		String cacheKey = WEBCACHE_KEY_LESSEE_HOUSE;
		return super.validationHouseForRenderText(houseNumber, cacheKey);
	}

	public String validateLesseeAllowLoad(
			@Read IndividualVO individualVO,
			@Read(key="optionType")String optionType)
	{
		String cacheKey = WEBCACHE_KEY_LESSEE_HOUSE;
		return super.validateIndividualLoadForRenderText(individualVO,cacheKey,optionType);
	}

	public String validateOrganizationLessee(@Read OrganizationVO organizationVO,
            @Read (key="optionType")String optionType){
			return super.validateOrganizationLoadForRenderText(organizationVO, WEBCACHE_KEY_LESSEE_HOUSE, optionType);
	}

	/**
	 * Function: 重新封装个人详细信息包括性别,兴趣爱好
	 * @param individualVO
	 * Create author:燕大为
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	private void wrapIndividualDetail(IndividualVO individual)
	{
		if(individual != null)
		{
			if(!BlankUtil.isBlank(individual.getSex()))
				individual.setSexDisplayValue(getSexDisplayValueById(individual.getSex()));
			String targetInterest = wrapInterest(individual.getInterest());
			individual.setInterestNameStr(targetInterest);
			if(!BlankUtil.isBlank(individual.getBirthDate()))
				individual.setBirthDateDisplayValue(DateUtil.convertDateToStr(individual.getBirthDate(), "yyyy-MM-dd"));
			if(!BlankUtil.isBlank(individual.getCertificateType()))
				individual.setCertificateTypeName(getCertifiCateTypeName(individual.getCertificateType()));
		}
	}

	/***
	 * Function:例:将兴趣爱好str=1,2,转换为str=打球,跳舞
	 * @param interest
	 * Create author:燕大为
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	private String wrapInterest(String srcInterest)
	{
		String targetInterest = "";
		if(!BlankUtil.isBlank(srcInterest))
		{
			List<InterestVO> list = new ArrayList<InterestVO>();
			filtrateExistentInterest(srcInterest, getAllInterestList(), list);
			StringBuffer sb = new StringBuffer();
			for(InterestVO interest : list)
			{
				sb.append(interest.getName()).append(",");
			}

			targetInterest = sb.toString().substring(0, sb.toString().length()-1);
		}
		return targetInterest;
	}

	/***
	 * Function: 重新封装企业详细信息包括性别
	 * @param OrganizationVO
	 * Create author:燕大为
	 * Create on:2008-6-13
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	private void wrapOrganizationDetail(OrganizationVO organization)
	{
		if(organization != null)
		{
			//法人证件类型
			if(!BlankUtil.isBlank(organization.getCertificateType()))
				organization.setCertificateTypeName(getCertifiCateTypeName(organization.getCertificateType()));
			//法人性别
			if(!BlankUtil.isBlank(organization.getSex()))
				organization.setSexDisplayValue(getSexDisplayValueById(organization.getSex()));
			//法人出生日期
			if(!BlankUtil.isBlank(organization.getCorporationBirthDate()))
				organization.setCorporationBirthDateDisplayValue(DateUtil.convertDateToStr(organization.getCorporationBirthDate(), "yyyy-MM-dd"));

			//代理人性别
			if(!BlankUtil.isBlank(organization.getConsignerSex()))
				organization.setConsignerSexDisplayValue(getSexDisplayValueById(organization.getConsignerSex()));
			//代理人证件类型
			if(!BlankUtil.isBlank(organization.getConsignerCertificateType()))
				organization.setConsignerCertificateTypeName(getCertifiCateTypeName(organization.getConsignerCertificateType()));
		}
	}

	/**
	 * Function: 过滤掉已删除的缓存中住房资料
	 * @return
	 * Create author:燕大为
	 * Create on:2008-6-3
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
   private LinkedList<CustomerHouseVO> getLesseeHouseListCacheBarringDeleteStatus()
   {
	   LinkedList<CustomerHouseVO> list = (LinkedList<CustomerHouseVO>) getRequest()
		.getSession().getAttribute(WEBCACHE_KEY_LESSEE_HOUSE);

		LinkedList<CustomerHouseVO> noDelList = new LinkedList<CustomerHouseVO>();

		//把缓存中住房资料操作状态为已删除的过滤掉
		if (list != null) {
			for (CustomerHouseVO house : list) {
				if (house.getOpratorStatus().equals(ICacheManage.DELETE)) {
					continue;
				}
				noDelList.add(house);
			}
		}

		return noDelList;
   }

	private ILesseeService lesseeService;

	public void setLesseeService(ILesseeService lesseeService) {
		this.lesseeService = lesseeService;
	}




}
